package com.gancp.utills;


import org.apache.commons.lang3.StringUtils;
import sun.misc.BASE64Encoder;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Created by GCP on 2018/4/29.
 */
public class Md5Utils {

    private static String MD5_TYPE = "MD5";

    public static String enctyptCode(byte[] bytes) throws NoSuchAlgorithmException {
        if (bytes == null) {
            return "";
        }
        MessageDigest messageDigest = MessageDigest.getInstance( MD5_TYPE );
        BASE64Encoder encoder = new BASE64Encoder();
        byte[] encryptBytes = messageDigest.digest( bytes );
        String result = encoder.encode( encryptBytes );
        return result;
    }

    public static String enctyptSig(byte[] bytes) throws NoSuchAlgorithmException, UnsupportedEncodingException {
        if (bytes == null) {
            return "";
        }
        MessageDigest messageDigest = MessageDigest.getInstance( MD5_TYPE );
        byte[] encryptBytes = messageDigest.digest( bytes );
        String result = new String( encryptBytes, "utf-8" );
        return result;
    }

    public static boolean compare(String inputPwd, String dbPwd) throws UnsupportedEncodingException, NoSuchAlgorithmException {
        if (StringUtils.isEmpty( inputPwd )) {
            return false;
        }
        String encryptInputPwd = enctyptCode( inputPwd.getBytes( "utf-8" ) );
        return dbPwd.equals( encryptInputPwd );
    }
}
